package com.sky.interceptor;

import com.sky.constant.JwtClaimsConstant;
import com.sky.context.BaseContext;
import com.sky.properties.JwtProperties;
import com.sky.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author 梁科
 * @Version 1.0
 * @ Date 2025/10/26 18:30
 */
@Component
@Slf4j
public class JwtTokenUserInterceptor implements HandlerInterceptor {
    @Resource
    private JwtProperties jwtProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 判断拦截到的是控制器方法还是其它资源
        // 如果是其它资源则放行
        if (!(handler instanceof HandlerMethod)){
            return true;
        }
        try {
            // 从请求头中获取前端传来的token
            String token = request.getHeader(jwtProperties.getUserTokenName());
            log.info("jwt校验:{}", token);
            Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);
            Long userId = Long.valueOf(claims.get(JwtClaimsConstant.USER_ID).toString());
            log.info("userId = {}",userId);
            // 将用户id放到threadLocal中，以便后续使用
            BaseContext.setCurrentId(userId);
            return true;
        } catch (Exception e) {
            // 返回不可访问的状态码401
            response.setStatus(401);
            return false;
        }
    }
}
